<template>
  <view class="contactless-parking-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="无感停车" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">

            
            <!-- 搜索框 -->
            <view class="filter-item">
              <up-search v-model="searchForm.searchValue" :clearabled="true" :showAction="true" 
                placeholder="请输入手机号或车牌号" 
                @custom="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  <up-button type="default" size="small" @click="handleClear" style="margin-left: 5px;">重置</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 功能切换 -->
            <view class="filter-item">
              <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 开启记录列表 -->
      <view class="contactless-parking-list" v-if="currentTab === 0">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
            <view class="status active">已开启</view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">开启时间：</text>
                <text class="value">{{ item.enableTime }}</text>
              </view>
              <view class="item">
                <text class="label">自动扣款限额：</text>
                <text class="value">{{ item.limitAmount }}元</text>
              </view>
              <view class="item">
                <text class="label">已自动扣款金额：</text>
                <text class="value amount">{{ item.deductedAmount }}元</text>
              </view>
              <view class="item">
                <text class="label">绑定用户：</text>
                <text class="value">{{ item.userName }}</text>
              </view>
              <view class="item">
                <text class="label">手机号：</text>
                <text class="value">{{ item.userPhone }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="查看扣款记录" class="custom-style" @click.stop="viewDeductionRecords(item)"></up-button>
                <up-button type="warning" text="修改限额" class="custom-style" @click.stop="modifyLimit(item)"></up-button>
                <up-button type="danger" text="关闭无感停车" class="custom-style" @click.stop="closeContactless(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 关闭记录列表 -->
      <view class="contactless-parking-list" v-if="currentTab === 1">
        <!-- 筛选条件 -->
        <view class="closed-filter-section">
          <view class="filter-row">
            <up-input v-model="closedSearchForm.userAccount" placeholder="用户账号" clearable></up-input>
            <up-input v-model="closedSearchForm.plateNumber" placeholder="车牌号" clearable></up-input>
          </view>
          <view class="filter-row">
            <up-input v-model="closedSearchForm.operator" placeholder="操作人" clearable></up-input>
            <up-datetime-picker v-model="closedSearchForm.closeTimeRange" mode="range" placeholder="关闭时间区间"></up-datetime-picker>
          </view>
          <view class="filter-actions">
            <up-button type="primary" @click="searchClosedRecords">查询</up-button>
            <up-button type="default" @click="resetClosedSearch">重置</up-button>
          </view>
        </view>
        
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
            <view class="status closed">已关闭</view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">关闭的用户账号：</text>
                <text class="value">{{ item.userAccount }}</text>
              </view>
              <view class="item">
                <text class="label">手机号：</text>
                <text class="value">{{ item.userPhone }}</text>
              </view>
              <view class="item">
                <text class="label">关闭时间：</text>
                <text class="value">{{ item.closeTime }}</text>
              </view>
              <view class="item">
                <text class="label">操作人：</text>
                <text class="value">{{ item.operator }}</text>
              </view>
              <view class="item">
                <text class="label">关闭原因：</text>
                <text class="value">{{ item.closeReason || '用户主动关闭' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 扣款记录弹窗 -->
    <deduction-records-modal ref="deductionRecordsModal" :show="showDeductionRecordsModal" 
      @update:show="(val) => showDeductionRecordsModal = val" :recordsList="selectedDeductionRecords" @close="handleDeductionRecordsModalClose" />
    
    <!-- 修改限额弹窗 -->
    <up-popup :show="showModifyLimitModal" @update:show="(val) => showModifyLimitModal = val" overlay mode="center" :round="10" closeable closeOnClickOverlay>
      <view class="modify-limit-modal">
        <view class="modal-title">修改自动扣款限额</view>
        <view class="modal-content">
          <view class="current-info">
            <text>当前限额：{{ currentVehicle?.limitAmount }}元</text>
          </view>
          <view class="input-section">
            <up-input v-model="newLimitAmount" placeholder="请输入新的限额" type="number"></up-input>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="default" @click="showModifyLimitModal = false">取消</up-button>
          <up-button type="primary" @click="confirmModifyLimit">确定</up-button>
        </view>
      </view>
    </up-popup>
    
    <!-- 关闭无感停车确认弹窗 -->
    <up-popup :show="showCloseContactlessModal" @update:show="(val) => showCloseContactlessModal = val" overlay mode="center" :round="10" closeable closeOnClickOverlay>
      <view class="confirm-modal">
        <view class="modal-title">关闭无感停车确认</view>
        <view class="modal-content">
          <text>确定要关闭车牌 {{ currentVehicle?.plateNumber }} 的无感停车功能吗？</text>
        </view>
        <view class="modal-footer">
          <up-button type="default" @click="showCloseContactlessModal = false">取消</up-button>
          <up-button type="danger" @click="confirmCloseContactless">确定</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import DeductionRecordsModal from './components/DeductionRecordsModal.vue';

// 搜索表单
const searchForm = reactive({
  searchValue: '', // 搜索值（支持手机号和车牌号模糊搜索）
});

// 关闭记录搜索表单
const closedSearchForm = reactive({
  userAccount: '', // 用户账号
  plateNumber: '', // 车牌号
  operator: '', // 操作人
  closeTimeRange: [], // 关闭时间区间
});

// 选项卡数据
const tabsList = [
  { name: '开启记录' },
  { name: '关闭记录' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 选中车辆的扣款记录
const selectedDeductionRecords = ref([]);

// 扣款记录弹窗引用
const deductionRecordsModal = ref(null);
const showDeductionRecordsModal = ref(false);

// 修改限额弹窗
const showModifyLimitModal = ref(false);
const currentVehicle = ref(null);
const newLimitAmount = ref('');

// 关闭无感停车弹窗
const showCloseContactlessModal = ref(false);

// 处理搜索
const handleSearch = () => {
  if (!searchForm.searchValue) {
    uni.showToast({
      title: '请输入手机号或车牌号',
      icon: 'none'
    });
    return;
  }
  paging.value.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.searchValue = '';
  currentList.value = [];
};

// 处理标签页切换
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }
  
  currentTab.value = newIndex;
  
  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

// 查看扣款记录
const viewDeductionRecords = (item) => {
  // 模拟获取车辆扣款记录
  selectedDeductionRecords.value = generateMockDeductionRecords(item);
  showDeductionRecordsModal.value = true;
};

// 处理扣款记录弹窗关闭事件
const handleDeductionRecordsModalClose = () => {
  console.log('扣款记录弹窗已关闭');
};

// 修改限额
const modifyLimit = (item) => {
  currentVehicle.value = item;
  newLimitAmount.value = item.limitAmount;
  showModifyLimitModal.value = true;
};

// 确认修改限额
const confirmModifyLimit = () => {
  if (!newLimitAmount.value || parseFloat(newLimitAmount.value) <= 0) {
    uni.showToast({
      title: '请输入有效的限额',
      icon: 'none'
    });
    return;
  }
  
  // 模拟API调用
  uni.showLoading({ title: '修改中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '限额修改成功',
      icon: 'success'
    });
    showModifyLimitModal.value = false;
    // 更新列表数据
    if (currentVehicle.value) {
      const index = currentList.value.findIndex(item => item.id === currentVehicle.value.id);
      if (index !== -1) {
        currentList.value[index].limitAmount = newLimitAmount.value;
      }
    }
  }, 1000);
};

// 关闭无感停车
const closeContactless = (item) => {
  currentVehicle.value = item;
  showCloseContactlessModal.value = true;
};

// 确认关闭无感停车
const confirmCloseContactless = () => {
  // 模拟API调用
  uni.showLoading({ title: '关闭中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '无感停车已关闭',
      icon: 'success'
    });
    showCloseContactlessModal.value = false;
    // 更新列表数据
    if (currentVehicle.value) {
      const index = currentList.value.findIndex(item => item.id === currentVehicle.value.id);
      if (index !== -1) {
        // 从列表中移除该项
        currentList.value.splice(index, 1);
      }
    }
  }, 1000);
};

// 查询关闭记录
const searchClosedRecords = () => {
  paging.value.reload();
};

// 重置关闭记录搜索
const resetClosedSearch = () => {
  closedSearchForm.userAccount = '';
  closedSearchForm.plateNumber = '';
  closedSearchForm.operator = '';
  closedSearchForm.closeTimeRange = [];
  currentList.value = [];
};

// 生成模拟扣款记录数据
const generateMockDeductionRecords = (vehicle) => {
  const count = Math.floor(Math.random() * 10) + 1; // 1-10条记录
  return Array.from({ length: count }, (_, i) => ({
    deductionId: `${Math.floor(Math.random() * 1000000)}`,
    parkingLocation: `${['南海区', '顺德区', '禅城区', '三水区'][Math.floor(Math.random() * 4)]}停车场${Math.floor(Math.random() * 100) + 1}号`,
    deductionTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
    amount: (Math.random() * 20).toFixed(2),
    parkingDuration: `${Math.floor(Math.random() * 5) + 1}小时${Math.floor(Math.random() * 60)}分钟`,
    status: Math.random() > 0.1 ? '成功' : '失败'
  }));
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理搜索参数
    const params = {
      pageNo,
      pageSize,
      searchValue: searchForm.searchValue,
      tabIndex: currentTab.value,
      ...closedSearchForm
    };
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getContactlessParkingList(params);
    // const data = result.data;
    
    // 模拟数据
    let mockData;
    
    if (currentTab.value === 0) {
      // 开启记录数据
      mockData = {
        total: 50,
        list: Array.from({ length: 10 }, (_, i) => {
          // 生成随机车牌号
          const randomPlate = `粤${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(Math.random() * 10000).toString().padStart(5, '0')}`;
          // 生成随机手机号
          const randomPhone = `1${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`;
          // 生成随机用户名
          const randomUser = `用户${Math.floor(Math.random() * 1000) + 1}`;
          
          // 如果有搜索值，模拟模糊搜索匹配
          let plateNumber = randomPlate;
          let userPhone = randomPhone;
          let userName = randomUser;
          
          // 如果有搜索值，确保至少有一个字段包含搜索值
          if (searchForm.searchValue) {
            // 每三条数据中的一条，将搜索值插入到车牌号中
            if (i % 3 === 0) {
              plateNumber = `粤${searchForm.searchValue}${Math.floor(Math.random() * 1000)}`;
            }
            // 每三条数据中的一条，将搜索值插入到手机号中
            else if (i % 3 === 1) {
              userPhone = `1${searchForm.searchValue}${Math.floor(Math.random() * 1000)}`;
            }
          }
          
          return {
            id: `active-${pageNo}-${i}`,
            plateNumber: plateNumber,
            userName: userName,
            userPhone: userPhone,
            enableTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
            limitAmount: (Math.random() * 500 + 100).toFixed(0),
            deductedAmount: (Math.random() * 200).toFixed(2)
          };
        })
      };
    } else {
      // 关闭记录数据
      mockData = {
        total: 30,
        list: Array.from({ length: 8 }, (_, i) => {
          // 生成随机车牌号
          const randomPlate = `粤${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(Math.random() * 10000).toString().padStart(5, '0')}`;
          // 生成随机用户账号
          const randomAccount = `user${Math.floor(Math.random() * 1000) + 1}@example.com`;
          // 生成随机手机号
          const randomPhone = `1${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`;
          
          // 使用筛选表单的值或随机值
          let plateNumber = closedSearchForm.plateNumber || randomPlate;
          let userAccount = closedSearchForm.userAccount || randomAccount;
          let userPhone = randomPhone;
          
          // 如果有搜索值，确保至少有一个字段包含搜索值
          if (searchForm.searchValue) {
            // 每三条数据中的一条，将搜索值插入到车牌号中
            if (i % 3 === 0) {
              plateNumber = `粤${searchForm.searchValue}${Math.floor(Math.random() * 1000)}`;
            }
            // 每三条数据中的一条，将搜索值插入到用户账号中
            else if (i % 3 === 1) {
              userAccount = `user${searchForm.searchValue}${Math.floor(Math.random() * 100)}@example.com`;
            }
            // 每三条数据中的一条，将搜索值插入到手机号中
            else {
              userPhone = `1${searchForm.searchValue}${Math.floor(Math.random() * 1000)}`;
            }
          }
          
          return {
            id: `closed-${pageNo}-${i}`,
            plateNumber: plateNumber,
            userAccount: userAccount,
            userPhone: userPhone,
            closeTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
            operator: closedSearchForm.operator || `管理员${Math.floor(Math.random() * 10) + 1}`,
            closeReason: ['用户主动关闭', '系统自动关闭', '管理员关闭', '账户异常关闭'][Math.floor(Math.random() * 4)]
          };
        })
      };
    }
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取无感停车列表数据失败:', error);
    paging.value.complete(false);
  }
};

onMounted(() => {
  // 页面加载时自动加载初始数据
  queryList(1, 10);
});
</script>

<style lang="scss" scoped>
.contactless-parking-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    margin-bottom: 10px;
    
    .filter-item {
      margin-bottom: 10px;
    }
    
    .search-tip {
      font-size: 14px;
      color: #666;
      padding: 5px 0;
    }
  }
  
  .closed-filter-section {
    padding: 20px;
    background-color: #fff;
    margin-bottom: 10px;
    border-radius: 8px;
    
    .filter-row {
      display: flex;
      gap: 10px;
      margin-bottom: 10px;
      
      > * {
        flex: 1;
      }
    }
    
    .filter-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
    }
  }
}

.contactless-parking-list {
  padding: 20px;
  
  .list-item-card {
    .card-content-box {
      .card-footer {
        padding: 15px 20px;
        border-top: 1px solid #eee;
        display: flex;
        justify-content: flex-end;
        
        .operate {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          
          .custom-style {
            font-size: 12px;
            padding: 5px 10px;
          }
        }
      }
    }
  }
}

.modify-limit-modal {
  width: 80vw;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  
  .modal-title {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-content {
    margin-bottom: 20px;
    
    .current-info {
      text-align: center;
      margin-bottom: 15px;
      color: #666;
    }
    
    .input-section {
      margin-bottom: 10px;
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: space-around;
  }
}

.confirm-modal {
  width: 80vw;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  
  .modal-title {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-content {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-footer {
    display: flex;
    justify-content: space-around;
  }
}
</style>